#!/bin/bash
#==============================================================#
# File      :   ssh
# Desc      :   write terraform ssh config to ~/.ssh/pigsty_config
# Ctime     :   2024-11-23
# Mtime     :   2024-08-22
# Path      :   terraform/ssh
# License   :   AGPLv3 @ https://pigsty.io/docs/about/license
# Copyright :   2018-2025  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#
PROG_NAME="$(basename $0)"
PROG_DIR="$(cd $(dirname $0) && pwd)"
PASSWORD='PigstyDemo4'

# Write Terraform SSH config to ~/.ssh/pigsty_config
cd "$PROG_DIR"
outputs=$(terraform output -json)

SSH_CONFIG_FILE="$HOME/.ssh/pigsty_config"
> "$SSH_CONFIG_FILE"

for key in $(echo "$outputs" | jq -r 'keys[]'); do
  ip=$(echo "$outputs" | jq -r ".${key}.value")
  shortname=$(echo "$key" | sed 's/_ip$//')
  hostname="${shortname}"
  {
    echo "Host $hostname"
    echo "  HostName $ip"
    echo "  User root"
    echo ""
  } >> "$SSH_CONFIG_FILE"
done

cat "$SSH_CONFIG_FILE"

for key in $(echo "$outputs" | jq -r 'keys[]'); do
  ip=$(echo "$outputs" | jq -r ".${key}.value")
  sshpass -p "$PASSWORD" ssh-copy-id -o StrictHostKeyChecking=no root@"$ip"
done
